import logging
import os
import socket
import sys
import threading

import framework

# logging日志的配置
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s",
    filename="log.txt",
    filemode="w",
)


def getReqSocket(newSockt, ipPort):
    print(ipPort)
    recvData = newSockt.recv(4096)
    if len(recvData) == 0:
        print("关闭浏览器！", ipPort)
        newSockt.close()
        return
    recvClientContent = recvData.decode("utf-8")
    reqList = recvClientContent.split(" ", 2)
    reqUrl = reqList[1]
    if reqUrl == "/":
        reqUrl = "/index.html"
    print("客服端接收的数据：", reqUrl)
    # with open("static/index.html", "rb") as file:
    if reqUrl.endswith(".html"):
        logging.info("动态资源请求:" + reqUrl)
        print("动态资源")
        env = {
            "reqUrl": reqUrl,
        }
        status, headers, responseBoy = framework.handle_request(env)
        responseLine = "HTTP/1.1 %s\r\n" % status
        responseHeader = ""
        for header in headers:
            responseHeader += "%s: %s\r\n" % header
        responseData = (responseLine + responseHeader + "\r\n").encode(
            "utf-8"
        ) + responseBoy
        newSockt.send(responseData)
        newSockt.close()
        print("发送成功！")
    else:
        logging.info("静态资源请求:" + reqUrl)
        try:
            with open("static" + reqUrl, "rb") as file:
                fileData = file.read()
        except Exception as e:
            responseLine = "HTTP/1.1 404 Not Found\r\n"
            responseHeader = "Server: PWS1.0\r\n"
            with open("static/error.html", "rb") as file:
                fileData = file.read()
            responseBody = fileData
            responseData = (responseLine + responseHeader + "\r\n").encode(
                "utf-8"
            ) + responseBody
            newSockt.send(responseData)
        else:
            responseLine = "HTTP/1.1 200 OK\r\n"
            responseHeader = "Server: PWS1.0\r\n"
            responseBody = fileData
            responseData = (responseLine + responseHeader + "\r\n").encode(
                "utf-8"
            ) + responseBody
            newSockt.send(responseData)
        finally:
            print("关闭套接字", ipPort)
            newSockt.close()


def main():
    path = os.getcwd()
    print(path)
    tcpServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcpServerSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    params = sys.argv
    if len(params) != 2:
        print("命令执行格式应为：XXXXX.py 8080")
        logging.warning("用户在命令行启动程序参数个数不正确!")
        return
    if not params[1].isdigit():
        print("命令执行格式应为：XXXXX.py 8080")
        logging.warning("用户在命令行启动程序参数不是数字字符串!")
        return
    port = int(params[1])
    tcpServerSocket.bind(("", port))
    tcpServerSocket.listen(128)
    while True:
        newSockt, ipPort = tcpServerSocket.accept()
        subThreading = threading.Thread(target=getReqSocket, args=(newSockt, ipPort))
        subThreading.setDaemon(True)
        subThreading.start()


if __name__ == "__main__":
    main()
